from tortoise.models import Model
from tortoise import fields
from datetime import datetime


class ProductUnit(Model):
    """
    商品单位价格模型
    """
    unitid = fields.IntField(pk=True, description="单位ID")
    pid = fields.IntField(description="商品ID")
    unit = fields.CharField(max_length=20, null=True, description="单位")
    unitprice = fields.DecimalField(max_digits=10, decimal_places=2, null=True, description="单位价格")
    del_flag = fields.CharField(max_length=1, default="0", description="删除标志(0代表存在 2代表删除)")
    create_by = fields.CharField(max_length=64, null=True, description="创建者")
    create_time = fields.DatetimeField(null=True, description="创建时间")
    update_by = fields.CharField(max_length=64, null=True, description="更新者")
    update_time = fields.DatetimeField(null=True, description="更新时间")
    remark = fields.CharField(max_length=128, null=True, description="备注")

    class Meta:
        table = "wms_product_unit"
        table_description = "商品单位价格表"

    def __str__(self):
        return f"ProductUnit(unitid={self.unitid}, pid={self.pid}, unit={self.unit})"

    @property
    def is_deleted(self) -> bool:
        """判断单位是否被删除"""
        return self.del_flag == "2"

    @classmethod
    async def get_by_product(cls, pid: int):
        """根据商品ID获取所有单位"""
        return await cls.filter(pid=pid, del_flag__not="2").all()

    @classmethod
    async def get_active_units(cls):
        """获取所有激活的单位"""
        return await cls.filter(del_flag__not="2").all()